package top.wilbert.collegelink.classification.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import top.wilbert.collegelink.classification.entity.RegionEntity;
import top.wilbert.collegelink.common.utils.PageUtils;
import top.wilbert.collegelink.common.utils.Query;

import top.wilbert.collegelink.classification.dao.OccupationDao;
import top.wilbert.collegelink.classification.entity.OccupationEntity;
import top.wilbert.collegelink.classification.service.OccupationService;


@Service("occupationService")
public class OccupationServiceImpl extends ServiceImpl<OccupationDao, OccupationEntity> implements OccupationService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OccupationEntity> page = this.page(
                new Query<OccupationEntity>().getPage(params),
                new QueryWrapper<OccupationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<OccupationEntity> getListByPid(Integer pid) {
        List<OccupationEntity> occupationEntities = baseMapper.selectList(new QueryWrapper<OccupationEntity>().eq("pid", pid));
        return occupationEntities;
    }

    @Override
    public List<OccupationEntity> listWithTree() {

        //1、查出所有分类
        List<OccupationEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构
        //找到所有的一级分类
        List<OccupationEntity> level1Menus = entities.stream().filter((occupationEntity) -> {
            return occupationEntity.getPid().equals(-1);
        }).map((menu)->{
            menu.setChildren(getChildren(menu,entities));
            return menu;
        }).collect(Collectors.toList());

        return level1Menus;
    }


    //递归查出所有菜单的子菜单
    private List<OccupationEntity> getChildren(OccupationEntity root,List<OccupationEntity> all){
        List<OccupationEntity> children = all.stream().filter(occupationEntity -> {
            return occupationEntity.getPid().equals(root.getOccupationId());
        }).map(occupationEntity -> {
            //找到子菜单
            occupationEntity.setChildren(getChildren(occupationEntity,all));
            return occupationEntity;
        }).collect(Collectors.toList());

        return children;
    }

}